package com.mf.morefun.ui.person.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;
import com.mf.morefun.R;
import com.mf.morefun.adapter.ExchangeListAdapter;
import com.mf.morefun.base.BaseBusFragment;
import com.mf.morefun.bean.AchievementStatiscBean;
import com.mf.morefun.bean.ExchangeGiftBean;
import com.mf.morefun.bean.ExchangeListBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.bean.WorksBean;
import com.mf.morefun.bean.WorksListBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.requestbean.RequestAchievementBean;
import com.mf.morefun.requestbean.RequestExchangeGiftBean;
import com.mf.morefun.requestbean.RequestWorksBean;
import com.mf.morefun.ui.dohomework.HomeworkListActivity;
import com.mf.morefun.widget.NetErrorPop;
import com.mf.morefun.widget.RoundProcessDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import butterknife.BindView;

public class AchievementFragment extends BaseBusFragment {
    @BindView(R.id.tv_learn)
    TextView tvLearn;
    @BindView(R.id.tv_lianxu)
    TextView tvLianxu;
    @BindView(R.id.tv_luyin)
    TextView tvLuyin;
    @BindView(R.id.gv_achievement)
    GridView gvAchievement;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private ClassicsHeader mClassicsHeader = null;
    private int pageNo = 1;
    private SPUtils mSputils;
    private int totlePage = 1;
    private List<ExchangeListBean> mExchangeList = new ArrayList<>();
    private ExchangeListAdapter adapter;
    private RoundProcessDialog dialog;

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_achievement;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        mSputils = new SPUtils(getActivity());
        dialog = new RoundProcessDialog(getActivity(), "");
        mClassicsHeader = (ClassicsHeader) refreshLayout.getRefreshHeader();
        int delda = new Random().nextInt(7 * 24 * 60 * 60 * 1000);
        mClassicsHeader.setLastUpdateTime(new Date(System.currentTimeMillis() - delda));
        mClassicsHeader.setTimeFormat(new SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA));
        refreshLayout.getLayout().bringChildToFront(gvAchievement);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                initGetExchangeList(true);
                refreshLayout.setEnableLoadMore(true);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNo++;
                if (pageNo < totlePage) {
                    initGetExchangeList(false);
                } else {
                    if (null != refreshLayout) {
                        refreshLayout.finishLoadMore();
                        refreshLayout.finishRefresh();
                        refreshLayout.setEnableLoadMore(false);
                    }
                }
            }
        });
        gvAchievement.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //点击
            }
        });
    }

    @Override
    protected void initData() {
        initGetAchievementTj();
        adapter = new ExchangeListAdapter(getActivity(), mExchangeList);
        gvAchievement.setAdapter(adapter);
        pageNo = 1;
        initGetExchangeList(true);
    }

    private void initGetExchangeList(boolean isRefresh) {
        if (null != dialog && !dialog.isShow()){
            dialog.show();
        }
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.EXCHANGEGIFTHISTORY);
        RequestExchangeGiftBean requestWorksBean = new RequestExchangeGiftBean();
        requestWorksBean.setPageNo(pageNo);
        requestWorksBean.setPageSize(20);
        requestWorksBean.setOrderBy("a.update_date desc");
        RequestExchangeGiftBean.MfPrizeExchangeBean mfPrizeExchangeBean = new RequestExchangeGiftBean.MfPrizeExchangeBean();
        RequestExchangeGiftBean.MfPrizeExchangeBean.UserBean userBean = new RequestExchangeGiftBean.MfPrizeExchangeBean.UserBean();
        userBean.setId(mSputils.getString(Configuration.USERID));
        mfPrizeExchangeBean.setUser(userBean);
        requestWorksBean.setMfPrizeExchange(mfPrizeExchangeBean);
        params.setBodyContent(JSON.toJSONString(requestWorksBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (null != dialog && dialog.isShow()){
                    dialog.cancel();
                }
                if (null != refreshLayout){
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
                if (isRefresh){
                    mExchangeList.clear();
                }
                LogUtils.d(result);
                if (!StringUtils.isEmpty(result)){
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0){
                        if (!StringUtils.isEmpty(resultBean.getResult())){
                            ExchangeGiftBean worksBean = JSON.parseObject(resultBean.getResult(), ExchangeGiftBean.class);
                            if (!StringUtils.isEmpty(worksBean.getList())){
                                List<ExchangeListBean> worksListBeanList = JSON.parseArray(worksBean.getList(), ExchangeListBean.class);
                                mExchangeList.addAll(worksListBeanList);
                            }
                            totlePage = worksBean.getTotalPage();
                        }else {
                            ToastUtils.show(getActivity(), "数据为空", 100);
                        }
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != dialog && dialog.isShow()){
                    dialog.cancel();
                }
                if (null != refreshLayout){
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void initGetAchievementTj() {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.ACHIEVEMENTSTATISTICS);
        RequestAchievementBean bean = new RequestAchievementBean();
        bean.setId(mSputils.getString(Configuration.USERID));
        params.setBodyContent(JSON.toJSONString(bean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    AchievementStatiscBean achievementStatiscBean = JSON.parseObject(result, AchievementStatiscBean.class);
                    if (achievementStatiscBean.getErrorCode() == 0){
                        tvLearn.setText(achievementStatiscBean.getResult().getLearningDays() + "天");
                        tvLianxu.setText(achievementStatiscBean.getResult().getContinuousLlearningDays() + "天");
                        tvLuyin.setText(achievementStatiscBean.getResult().getCountRecordBooks() + "本");
                    }else {
                        ToastUtils.show(getActivity(), achievementStatiscBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(getActivity());
                    errorPop.showPop("");
                    break;
            }
        }
    };

}
